package com.yangl.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.yangl.domain.User;
import com.yangl.service.UserService;

import java.util.List;

@Controller  
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/")
    public ModelAndView getIndex() {
        ModelAndView mav = new ModelAndView("all");
        List<User> userall = userService.selectUserAll();
        mav.addObject("userall", userall);
//        User user = userService.selectUserById(3);
//        mav.addObject("user", user);
        return mav;
    }

    @RequestMapping("all")
    public ModelAndView getAll() {
        ModelAndView mav = new ModelAndView("all");
        List<User> userall = userService.selectUserAll();
        mav.addObject("userall", userall);
        return mav;
    }

    @RequestMapping("add")
    public String addUser() {
        return "add";
    }


    @RequestMapping("modify")
    public String modify(int tid, HttpServletRequest request) {
        try {
            User user = userService.selectUserById(tid);
            request.setAttribute("user", user);
            return "modify";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败！具体异常信息：" + e.getMessage());
            return "result";
        }
    }


    @RequestMapping("update")
    public String update(User user, HttpServletRequest request) {
        try {
            userService.update(user);
//            List<User> userall = userService.selectUserAll();
//            request.setAttribute("userall", userall);
        } catch (Exception e) {
            e.printStackTrace();
//            request.setAttribute("InfoMessage", "更新信息失败！具体异常信息：" + e.getMessage());
        } finally {
            return "bootstrap/homepage";
        }
    }

    @RequestMapping("save")
    public String userSave(HttpServletRequest request) {
        User user = new User();
        user.setUserName(request.getParameter("userName"));
        user.setUserPassword(request.getParameter("userPassword"));
        userService.addUser(user);
        return "bootstrap/homepage";
    }

    @RequestMapping("del")
    public String deleteUserById(int tid, HttpServletRequest request) {
        try {
            userService.deleteUserById(tid);
            List<User> userall = userService.selectUserAll();
            request.setAttribute("userall", userall);
        } catch (Exception e) {
            e.printStackTrace();
//            request.setAttribute("InfoMessage", "删除信息失败！具体异常信息：" + e.getMessage());
        } finally {
            return "all";
        }
    }
}